package com.simtop.controller;

import com.simtop.common.ServerResponse;
import com.simtop.pojo.File;
import com.simtop.pojo.User;
import com.simtop.service.FileService;
import com.simtop.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;


@Controller
@RequestMapping("/user")
@CrossOrigin
public class FileController {

    @Autowired
    private FileService fileService;
    /**
     * 文件下载
     * @param id
     * @param response
     * @return
     * @throws UnsupportedEncodingException
     */
    @GetMapping("/download/{id}")
    public ServerResponse<Object> downLoad(@PathVariable("id") Integer id, HttpServletResponse response, HttpServletRequest request) {
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt, User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        String filename=fileService.selectFileById(id);
        java.io.File file = new java.io.File(filename);
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            try {
                response.setHeader("Content-Disposition","attachment;fileName=" + java.net.URLEncoder.encode(filename,"UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println("----------file download---" + filename);//打印文件下载信息
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @PostMapping("/addfile")
    @ResponseBody
    public ServerResponse<String> fileAdd(com.simtop.pojo.File file, HttpServletRequest request){
        String token = request.getHeader("Authorization");
        String jwt = token.substring(token.lastIndexOf(" ")+1);
        User u = JwtUtil.unsign(jwt, User.class);
        if(u == null){
            return ServerResponse.createByErrorMsg("token无效");
        }
        System.out.println(file);
        return fileService.addFile(file);
    }

    /**
     * 文件上传
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public ServerResponse<String> fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
//        String token = request.getHeader("Authorization");
//        String jwt = token.substring(token.lastIndexOf(" ")+1);
//        User u = JwtUtil.unsign(jwt, User.class);
//        if(u == null){
//            return ServerResponse.createByErrorMsg("token无效");
//        }
        String destFileName = null;
        String fileName = file.getOriginalFilename();
        String path = "E:\\wangjiahua\\";//TODO  文件存放路径
        java.io.File f = new java.io.File(path);
        destFileName = path + fileName;
        if (!f.exists()){
            f.mkdirs();
        }
        if (!file.isEmpty()){
            try {
                FileOutputStream fos = new FileOutputStream(path + fileName);
                InputStream in = file.getInputStream();
                int a = 0;
                if ((a = in.read()) != -1){
                    fos.write(a);
                }
                in.close();
                fos.close();
            } catch (IOException e) {
                return ServerResponse.createByErrorMsg("文件上传失败");
            }
        }
        boolean flag = fileService.addUpLoadFile(destFileName);
        System.out.println("statu"+flag);
        if (flag == true){
            return ServerResponse.createBySuccessMsg("上传成功");
        }
        return ServerResponse.createByErrorMsg("上传失败");
    }
}
